import hashlib
from model import BaseModel
from sqlalchemy import Column,Integer,String,ForeignKey,Boolean
from sqlalchemy.orm import relationship,backref
from tornado.options import options


class UserAndHosts(BaseModel):
    __tablename__ = 'user_and_hosts'
    id = Column(Integer,primary_key = True)
    uid = Column(Integer,ForeignKey('user.id'))
    hid = Column(Integer,ForeignKey('host_computer.id'))


class User(BaseModel):
    __tablename__ = 'user'
    id = Column(Integer,primary_key = True)
    password = Column(String(500))
    username = Column(String(200))
    is_superuser = Column(Boolean(False))
    hosts = relationship("HostComputer",secondary = "user_and_hosts",backref = backref("user"))

    def __repr__(self):
        return "<User(id='%d',name='%s',passwd='%s'')>" % (
            self.id,self.name,self.password,)

    def encrypt_password(self,password):
        salt = self.get_salt()
        password = password + salt
        return hashlib.sha512(password.encode('utf-8')).hexdigest()

    def set_password(self,password):
        self.password = self.encrypt_password(password)

    def get_salt(self):
        salt = options.salt
        return salt

    def check_password_is_correct(self,password):
        encrypt_password = self.encrypt_password(password)
        return self.password == encrypt_password


class Group(BaseModel):
    __tablename__ = 'group'

    id = Column(Integer,primary_key = True)
    name = Column(String(200))
    host_id = Column(Integer,ForeignKey('host_computer.id'))
    user_id = Column(Integer,ForeignKey('user.id'))
    hosts = relationship("HostComputer",backref = 'groups')
    users = relationship("User",backref = 'groups')

    def __repr__(self):
        return "<HostComputer(id='%d',name='%s'')>" % (
            self.id,self.name,)
